﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using XcoAppSpaces.Contracts.Exceptions;
using XcoAppSpaces.Contracts.Serialization;
using XcoAppSpaces.Contracts.Messaging;

namespace XcoAppSpaces.Core.Communication
{
	static class SerializationExtensions
	{
		public static byte[] SerializeCausalityContext(this IXcoSerializer serializer, CausalityContext causalityContext)
		{
			return Serialize<CausalityContext>(serializer, causalityContext);
		}

		public static CausalityContext DeserializeCausalityContext(this IXcoSerializer serializer, byte[] serializedCausalityContext)
		{
			return Deserialize<CausalityContext>(serializer, serializedCausalityContext);
		}

		public static byte[] SerializeMessageContent(this IXcoSerializer serializer, RemoteMessage content)
		{
			return Serialize<RemoteMessage>(serializer, content);
		}

		public static RemoteMessage DeserializeMessageContent(this IXcoSerializer serializer, byte[] serializedContent)
		{
			return Deserialize<RemoteMessage>(serializer, serializedContent);
		}

		private static byte[] Serialize<T>(IXcoSerializer serializer, T obj) where T : class
		{
			if (obj != null)
			{
				try
				{
					return serializer.Serialize(obj);
				}
				catch (Exception ex)
				{
					throw new XcoSerializationException("Error serializing message content: " + ex.Message, ex);
				}
			}
			return null;
		}

		private static T Deserialize<T>(IXcoSerializer serializer, byte[] serializedObj)
		{
			if (serializedObj != null)
			{
				try
				{
					return (T)serializer.Deserialize(serializedObj);
				}
				catch (Exception ex)
				{
					throw new XcoSerializationException("Error deserializing message content: " + ex.Message, ex);
				}
			}
			return default(T);
		}
	}
}
